package com.yss.service.impl;

import com.alibaba.fastjson.JSON;
import com.yss.adapter.AdapterExtraInfo;
import com.yss.adapter.template.INettyAdapterInfo;
import com.yss.adapter.template.INettyAdapterTemplate;
import com.yss.adapter.template.IRestAdapterInfo;
import com.yss.adapter.template.IRestAdapterTemplate;
import com.yss.config.CommandTypeConfig;
import com.yss.exception.RemotingException;
import com.yss.exception.RemotingTimeOutException;
import com.yss.netty.protocol.CommandType;
import com.yss.netty.protocol.SerType;
import com.yss.netty.util.Host;
import com.yss.pojo.BondDTO;
import com.yss.pojo.response.ResponseMessage;
import com.yss.service.IBondService;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;

@Service
public class BondServiceImpl implements IBondService {

    @Autowired
    private CommandTypeConfig commandTypeConfig;

    private INettyAdapterTemplate nettyAdapterTemplate;

    public BondServiceImpl() {
        nettyAdapterTemplate = new INettyAdapterTemplate();
    }

    @Override
    public Object computeBondDataWithNetty(BondDTO bondDTO) {
        AdapterExtraInfo info = new INettyAdapterInfo(commandTypeConfig.getNettyHostByCommandType(CommandType.BOND),
                SerType.JSON, CommandType.BOND, false, null, bondDTO
        );
        try {
            return nettyAdapterTemplate.handle(info);
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (RemotingTimeOutException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object computeBondDataWithRest(BondDTO bondDTO) {
        HttpPost httpPost = new HttpPost(commandTypeConfig.getRestHostByCommandType(CommandType.BOND).getResourceUrl());
        StringEntity entity = new StringEntity(JSON.toJSONString(bondDTO), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        IRestAdapterInfo iRestAdapterInfo = new IRestAdapterInfo();
        iRestAdapterInfo.setHttpPost(httpPost);

        IRestAdapterTemplate restAdapterTemplate = new IRestAdapterTemplate();

        try {
            return restAdapterTemplate.handle(iRestAdapterInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
